/*
 * @Author: sbotlp
 * @Email: sbotlp@sina.com
 * @Date: 2020-10-31 21:40:30
 * @LastEditTime: 2020-11-02 09:25:43
 * @Description: http://www.sbotlp.com.cn
 */
import { Module } from 'vuex'
import * as types from '../action.type'
import * as api from '@/api'
import { PayloadTypes, State } from '../state.type'
import { IGlobalState } from '../index'
const state: State = {
  list: [],
  allTime: 0
}
// State 当前状态 GlobalTypes根状态
const Payload: Module<State, IGlobalState> = {
  state,
  mutations: {
    [types.GET_PLAN_LIST](state: State, payload: Array<PayloadTypes>) {
      state.list = payload
      state.allTime = payload.map(item => item.time).reduce((prev, curr) => prev + curr, 0)
    },
    [types.DELETE_PLAN](state: State, payload: PayloadTypes) {
      state.list = state.list.filter((item: PayloadTypes) => item._id !== payload._id)
      state.allTime = state.list.map(item => item.time).reduce((prev, curr) => prev + curr, 0)
    },
    [types.ADD_PLAN](state: State, payload: PayloadTypes) {
      state.list = [...state.list, payload]
      state.allTime = state.list.map(item => item.time).reduce((prev, curr) => prev + curr, 0)
    },
  },
  actions: {
    async [types.GET_PLAN_LIST]({ commit }, payload: PayloadTypes) {
      const result = await api.getPlanList<State>()
      commit(types.GET_PLAN_LIST, result)
    },
    async [types.DELETE_PLAN] ({ commit }, payload: PayloadTypes) {
      await api.deletePlanList(payload._id)
      commit(types.DELETE_PLAN, payload)
    },
    async [types.ADD_PLAN] ({ commit }, payload: PayloadTypes) {
      await api.addPlanList(payload)
      commit(types.ADD_PLAN, payload)
    }
  }
}
export default Payload
